package com.springbootx.mybatis.config.aop;


import com.springbootx.mybatis.config.DataSourceRouting;
import com.springbootx.mybatis.config.DynamicDataSourceContextHolder;
import com.springbootx.mybatis.config.annotations.DataSource;
import com.springbootx.mybatis.config.transactional.ApplicationContextUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Tony.niu (hystrix0779@yeah.net)
 * @version V1.0
 * @date 2020/6/30
 **/
@Aspect
@Order(2)
@Component
public class DataSourceAop {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.springbootx.mybatis.config.annotations.DataSource)")
    public void dsPointCut() {

    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource != null) {
            DataSourceRouting routing= ApplicationContextUtil.getBean(DataSourceRouting.class);
            if (routing.isOpen()){
                routing.bindConnection(dataSource.value());
            }
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}